package com.lagou.config;

import com.alibaba.csp.sentinel.adapter.gateway.common.rule.GatewayFlowRule;
import com.alibaba.csp.sentinel.adapter.gateway.common.rule.GatewayRuleManager;
import com.alibaba.csp.sentinel.adapter.gateway.sc.SentinelGatewayFilter;
import com.alibaba.csp.sentinel.adapter.gateway.sc.exception.SentinelGatewayBlockExceptionHandler;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.http.codec.ServerCodecConfigurer;
import org.springframework.web.reactive.result.view.ViewResolver;

import javax.annotation.PostConstruct;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * 网关限流配置
 */
@Configuration
public class GatewayConfiguration {
    /**
     * 视图解析器
     */
    private List<ViewResolver> viewResolvers;

    /**
     * 服务编解码配置器
     */
    private ServerCodecConfigurer serverCodecConfigurer;

    /**
     * 构造GatewayConfiguration对象
     *
     * @param viewResolversProvider 视图解析器的提供者
     * @param serverCodecConfigurer 服务编解码配置器
     */
    public GatewayConfiguration(ObjectProvider<List<ViewResolver>> viewResolversProvider,
                                ServerCodecConfigurer serverCodecConfigurer) {
        this.viewResolvers = viewResolversProvider.getIfAvailable(Collections::emptyList);
        this.serverCodecConfigurer = serverCodecConfigurer;
    }

    /**
     * 创建异常处理器
     *
     * @return 异常处理器
     */
    @Bean
    @Order(-1)
    public SentinelGatewayBlockExceptionHandler sentinelGatewayBlockExceptionHandler() {
        return new SentinelGatewayBlockExceptionHandler(viewResolvers, serverCodecConfigurer);
    }

    /**
     * 创建Sentinel过滤器
     *
     * @return Sentinel过滤器
     */
    @Bean
    @Order(-1)
    public GlobalFilter sentinelGatewayFilter() {
        return new SentinelGatewayFilter();
    }

    /**
     * 初始化限流规则
     */
    @PostConstruct
    public void doInit() {
        initGatewayRules();
    }

    /**
     * 初始化限流规则
     */
    private void initGatewayRules() {
        Set<GatewayFlowRule> rules = new HashSet<>();
        rules.add(new GatewayFlowRule("lagou-service-code")
                .setCount(1)
                .setIntervalSec(30)
        );

        GatewayRuleManager.loadRules(rules);
    }
}
